package csc.traning.wpsj.tags;

import java.io.IOException;
import java.io.StringWriter;
import java.text.DecimalFormat;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class TagConvertMB extends SimpleTagSupport{

	private int value;

	public void setValue(int value) {
		this.value = value;
	}

	StringWriter sw = new StringWriter();

	@Override
	public void doTag() throws JspException, IOException {
		super.doTag();
		if(value != 0){
			/* Use value from attribute */
			JspWriter out = getJspContext().getOut();
			out.print(convert(value));
		}
	}
	
	private String convert(int size){
		double s = size/1000;
		double m = s/1024.0;
		double g = s/1048576.0;
		double t = s/1073741824.0;
		String hrSize = "";
		DecimalFormat dec = new DecimalFormat("0.00");
		if (t >= 1) {
	        hrSize = dec.format(t).concat("TB");
	    } else if (g >= 1) {
	        hrSize = dec.format(g).concat("GB");
	    } else if (m >= 1) {
	        hrSize = dec.format(m).concat("MB");
	    } else {
	        hrSize = dec.format(s).concat("KB");
	    }
		return hrSize;
	}
	
}
